package com.x.provider.customer.service.customer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.x.provider.api.customer.enums.LevelTypeEnum;
import com.x.provider.customer.mapper.CustomerLevelMapper;
import com.x.provider.customer.model.domain.customer.CustomerLevel;
import com.x.provider.customer.model.query.customer.CustomerLevelQuery;
import com.x.provider.customer.service.directory.LevelDefService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author: liushenyi
 * @date: 2022/10/27/14:16
 */
@Service
public class CustomerLevelServiceImpl implements CustomerLevelService {

    private final CustomerLevelMapper customerLevelMapper;
    private final LevelDefService levelDefService;

    public CustomerLevelServiceImpl(CustomerLevelMapper customerLevelMapper,
                                    LevelDefService levelDefService){
        this.customerLevelMapper = customerLevelMapper;
        this.levelDefService = levelDefService;
    }

    @Override
    public void addCustomerExp(Long customerId, Long exp) {
        CustomerLevel customerLevel = get(customerId);
        if (customerLevel == null){
            customerLevel = CustomerLevel.builder().exp(0L).level(0).build();
        }
        customerLevel.setExp(customerLevel.getExp() + exp);
        customerLevel.setLevel(levelDefService.calcLevel(LevelTypeEnum.GROWTH.getValue(), customerLevel.getExp()));
        save(customerLevel);
    }

    @Override
    public List<CustomerLevel> list(List<Long> customerIdList) {
        return list(CustomerLevelQuery.builder().customerIdList(customerIdList).build());
    }

    @Override
    public CustomerLevel get(Long customerId) {
        return get(CustomerLevelQuery.builder().customerId(customerId).build());
    }

    public CustomerLevel get(CustomerLevelQuery query){
        return customerLevelMapper.selectOne(build(query));
    }

    public List<CustomerLevel> list(CustomerLevelQuery query){
        return customerLevelMapper.selectList(build(query));
    }

    private LambdaQueryWrapper<CustomerLevel> build(CustomerLevelQuery query){
        LambdaQueryWrapper<CustomerLevel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (query.getCustomerId() != null){
            lambdaQueryWrapper = lambdaQueryWrapper.eq(CustomerLevel::getCustomerId, query.getCustomerId());
        }
        if (!CollectionUtils.isEmpty(query.getCustomerIdList())){
            lambdaQueryWrapper = lambdaQueryWrapper.in(CustomerLevel::getCustomerId, query.getCustomerIdList());
        }
        return lambdaQueryWrapper;
    }

    private void save(CustomerLevel customerLevel){
        if (customerLevel.getId() == null){
            customerLevelMapper.insert(customerLevel);
        }
        else {
            customerLevelMapper.updateById(customerLevel);
        }
    }

}
